import datetime
from sqlalchemy import desc,ForeignKey
from sqlalchemy.orm import relationship
from manager.app import db, Base




class Device(Base):
    __tablename__ = 'pt_device'
    device_id=db.Column(db.String(50))
    device_name = db.Column(db.String(50))
    device_type = db.Column(db.String(50))
    config_list = relationship("DeviceConfig",backref='pt_device')


    @classmethod
    def load_device_list(cls):
        return cls.query.all()

    @classmethod
    def find_device_by_id(cls, device_id):
        return cls.query.filter_by(device_id=device_id)

    def to_dict(self):
        return {
            "id":self.id,
            "device_id": self.id,
            "device_name": self.device_name,
            "device_type":self.device_type
        }



class DeviceConfig(Base):
    tablename__ = 'pt_device_config'
    config_id = db.Column(db.String(50))
    config_name = db.Column(db.String(50))
    config_code = db.Column(db.String(50))
    config_value = db.Column(db.String(50))
    device_id = db.Column(db.String(50), ForeignKey('pt_device.device_id'))

    @classmethod
    def load_device_cfg_list(cls):
        return cls.query.all()

    @classmethod
    def find_device_cfg_by_id(cls, id):
        return cls.query.filter_by(id=id).first()

    def to_dict(self):
        return {
            "config_id": self.config_id,
            "config_name": self.config_name,
            "config_code":self.config_code,
            "config_value": self.config_value
        }


class Action(Base):
    __tablename__ = 'pt_action'
    action_name = db.Column(db.String(50))
    action_type = db.Column(db.String(50))
    action_command = db.Column(db.String(200))
    action_params = db.Column(db.String(200))

    @classmethod
    def load_action_list(cls):
        return cls.query.all()

    @classmethod
    def find_action_by_id(cls, action_id):
        return cls.query.filter_by(id=action_id).first()

    def to_dict(self):
        return {
            "action_id": self.id,
            "action_name": self.action_name,
            "action_type":self.action_type,
            "action_command":self.action_command,
            "action_params":self.action_params
        }


class ActionInstance(Base):
    __tablename__ = 'pt_action_instance'
    action_name = db.Column(db.String(50))
    action_id = db.Column(db.String(50))
    action_command = db.Column(db.String(200))
    action_params = db.Column(db.String(200))
    start_time = db.Column(db.String(50))
    end_time = db.Column(db.String(50))
    result = db.Column(db.String(500))


    @classmethod
    def load_action_list(cls):
        return cls.query().all()
